package com.xdtech.common.utils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

public class InvokeUtil {
	public static Logger log = Logger.getLogger(InvokeUtil.class);  
	/**
	 * 反射调用类
	 * @param classNameOrBeanName
	 * @param methodName
	 * @param paramsInfo
	 * @return
	 */
    public static Object invokMethod(String classNameOrBeanName,String methodName, Class[] parameterTypes,Object[] parameterValues) {  
        Object object = null;  
        Class clazz = null;  
                //springId不为空先按springId查找bean  
        if (StringUtils.isNotBlank(classNameOrBeanName)) {
        	try {
        		 object = ApplicationContextUtil.getContext().getBean(classNameOrBeanName);
			} catch (Exception e) {
				//获取不到
				object = null;
			}
           
            if (object==null) {
                 try {  
                     clazz = Class.forName(classNameOrBeanName);  
                     object = clazz.newInstance();  
                 } catch (Exception e) {  
                     log.error("init object error "+e.getMessage());
                 }
			}
        }
       
        if (object == null) {  
            log.error("invoke error ,please check classNameOrBeanName value");  
            return null;  
        }  
        clazz = object.getClass();  
        Method method = null;  
        try {  
            method = clazz.getDeclaredMethod(methodName,parameterTypes);  
        } catch (NoSuchMethodException e) {  
            log.error(classNameOrBeanName+" obj method="+methodName+" get error");  
        } catch (SecurityException e) {  
            e.printStackTrace();  
        }  
        if (method != null) {  
            try {  
               return method.invoke(object,parameterValues);  
            } catch (IllegalAccessException e) {  
                e.printStackTrace();  
            } catch (IllegalArgumentException e) {  
                e.printStackTrace();  
            } catch (InvocationTargetException e) {  
                e.printStackTrace();  
            }  
        }  
        return null;
          
    }  
}
